#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys

from tdecore import KDE
from tdecore import TDEApplication, TDEAboutData, TDECmdLineArgs, TDEIcon, i18n

from tdeui import TDEMainWindow, TDEIconView, TDEIconViewItem, TDEIconViewSearchLine, TDEPopupMenu
from tdeui import KJanusWidget, KTextEdit, KStdAction

# def make_tde_version(major, minor, release):
    # return (major << 16) | (minor << 8) | release

# TODO: Support R14.1.3
# AT_LEAST_R14_1_4 = KDE.version() >= make_tde_version(14, 1, 4)

from PyTQt.tqt import *

import icons

PAGES_LOADED = list()
PAGE_ACTIONS = 0
PAGE_APPLICATIONS = 1
PAGE_CATEGORIES = 2
PAGE_DEVICES = 3
PAGE_EMBLEMS = 4
PAGE_MEDIA_TYPES = 5
PAGE_PLACES = 6
PAGE_STATUS = 7

CPP_SNIPPET_TEMPLATE = """
// TQt
#include <tqiconset.h>

// TDE
#include <kiconloader.h>
#include <tdeapplication.h>

TQIconSet icon = tdeApp->iconLoader()->loadIconSet(\"{}\", TDEIcon::Toolbar);
""".strip()

PYTHON_SNIPPET_TEMPLATE = """
from tdecore import TDEApplication, TDEIcon

icon = TDEApplication.tdeApplication().iconLoader().loadIconSet(\"{}\", TDEIcon.Toolbar)
""".strip()

SNIPPET_TEMPLATES = [
    CPP_SNIPPET_TEMPLATE,
    PYTHON_SNIPPET_TEMPLATE
]

def initialisePage(widget, codeEditor):
    layout = TQVBoxLayout(widget, 0, 4)
    searchLayout = TQHBoxLayout(None)

    iconBrowser = TDEIconView(widget, b"icon_view")
    iconBrowser.setResizeMode(TDEIconView.Adjust)
    iconBrowser.setAutoArrange(True)

    codeEditor.connect(iconBrowser, TQ_SIGNAL("selectionChanged(TQIconViewItem*)"), codeEditor.slotIconChanged)

    searchLabel = TQLabel(i18n("<b>Filter: </b>"), widget)
    search = TDEIconViewSearchLine(widget, iconBrowser)
    searchLayout.addWidget(searchLabel)
    searchLayout.addWidget(search)

    layout.addLayout(searchLayout)
    layout.addWidget(iconBrowser)

    iconBrowser.show()
    searchLabel.show()
    search.show()

def load_icons(icon_view, icons):
    icon_loader = TDEApplication.tdeApplication().iconLoader()
    for icon in icons:
        ic = icon_loader.loadIcon(icon, TDEIcon.MainToolbar)
        item = TDEIconViewItem(icon_view, TQString(icon), ic)

    icon_view.arrangeItemsInGrid()

class CodeSampleBox(TQWidget):

    def __init__(self, parent):
        TQFrame.__init__(self, parent)

        # Index in SNIPPET_TEMPLATES
        self.snippetIndex = 0
        self.currentIcon = None

        self.layout = TQVBoxLayout(self)
        group = TQHButtonGroup(i18n("Language"), self)

        cpp = TQRadioButton("C++", group)
        py = TQRadioButton("Python", group)

        # Numbers match index in SNIPPET_TEMPLATES
        group.insert(cpp, 0)
        group.insert(py, 1)

        group.connect(group, TQ_SIGNAL("clicked(int)"), self.slotLanguageChanged)
        group.setButton(0)

        self.editor = KTextEdit(self)
        self.editor.setReadOnly(True)
        # TODO(mio): Add setting for preview font (https://codeberg.org/supercell/icon_explorer/issues/3)
        self.editor.setFont(TQFont("monospace", 8))
        self.editor.setText(i18n("Select an icon"))
        self.editor.setWordWrap(TQTextEdit.NoWrap)

        self.layout.addWidget(group)
        self.layout.addWidget(self.editor)


    def slotLanguageChanged(self, id):
        self.snippetIndex = id
        if self.currentIcon:
            self.editor.setText(SNIPPET_TEMPLATES[self.snippetIndex].format(self.currentIcon))

    def slotIconChanged(self, iconViewItem):
        self.currentIcon = iconViewItem.text()
        self.editor.setText(SNIPPET_TEMPLATES[self.snippetIndex].format(self.currentIcon))


class MainWindow (TDEMainWindow):
    def __init__ (self):
        TDEMainWindow.__init__ (self)

        self.container = TQWidget(self)
        self.containerLayout = TQVBoxLayout(self.container)

        # TODO(mio): Move away from KJanusWidget (https://codeberg.org/supercell/icon_explorer/issues/4)
        self.kjanus = KJanusWidget(self.container, b"main_widget", KJanusWidget.Tabbed)
        self.containerLayout.addWidget(self.kjanus, 4)

        self.codeEditor = CodeSampleBox(self.container)
        self.containerLayout.addWidget(self.codeEditor, 2)

        # NOTE: actionsPage is the initial widget shown.
        self.actionsPage = self.kjanus.addPage(i18n("Actions"))
        self.applicationsPage = self.kjanus.addPage(i18n("Applications"))
        self.categoriesPage = self.kjanus.addPage(i18n("Categories"))
        self.devicesPage = self.kjanus.addPage(i18n("Devices"))
        self.emblemsPage = self.kjanus.addPage(i18n("Emblems"))
        self.mediaTypesPage = self.kjanus.addPage(i18n("Media Types"))
        self.placesPage = self.kjanus.addPage(i18n("Places"))
        self.statusPage = self.kjanus.addPage(i18n("Status"))

        initialisePage(self.actionsPage, self.codeEditor)
        initialisePage(self.applicationsPage, self.codeEditor)
        initialisePage(self.categoriesPage, self.codeEditor)
        initialisePage(self.devicesPage, self.codeEditor)
        initialisePage(self.emblemsPage, self.codeEditor)
        initialisePage(self.mediaTypesPage, self.codeEditor)
        initialisePage(self.placesPage, self.codeEditor)
        initialisePage(self.statusPage, self.codeEditor)

        self.connect(self.kjanus, TQ_SIGNAL("aboutToShowPage(TQWidget*)"), self.slotPreparePage)
        self.connect(TDEApplication.tdeApplication(), TQ_SIGNAL("iconChanged(int)"), self.slotIconChanged)

        fileMenu = TDEPopupMenu(self)
        KStdAction.close(self, TQ_SLOT("close()"), self.actionCollection()).plug(fileMenu)

        helpMenu = self.helpMenu("")

        self.menuBar().insertItem(i18n("&File"), fileMenu)
        self.menuBar().insertItem(i18n("&Help"), helpMenu)

        self.setCentralWidget(self.container)
        self.resize(640, 480)


    #### SLOTS #################################################################

    def slotIconChanged(self, group):
        if group != TDEIcon.MainToolbar:
            return

        for index in PAGES_LOADED:
            page_widget = self.kjanus.pageWidget(index)
            icon_view = page_widget.child(b"icon_view")
            icon_view.clear()

        PAGES_LOADED.clear()

        current_index = self.kjanus.activePageIndex()
        current_page = self.kjanus.pageWidget(current_index)
        icon_view = current_page.child(b"icon_view")

        print(f"[DEBUG] current_index = {current_index}")

        # ...grumble... don't like this
        # TODO(mio): store an index->icons.{ICON} map?
        if current_index == PAGE_ACTIONS:
            load_icons(icon_view, icons.ACTION_ICONS)
        elif index == PAGE_APPLICATIONS:
            load_icons(icon_view, icons.APPLICATION_ICONS)
        elif index == PAGE_CATEGORIES:
            load_icons(icon_view, icons.CATEGORY_ICONS)
        elif index == PAGE_DEVICES:
            load_icons(icon_view, icons.DEVICE_ICONS)
        elif index == PAGE_EMBLEMS:
            load_icons(icon_view, icons.EMBLEM_ICONS)
        elif index == PAGE_MEDIA_TYPES:
            load_icons(icon_view, icons.MEDIA_TYPE_ICONS)
        elif index == PAGE_PLACES:
            load_icons(icon_view, icons.PLACE_ICONS)
        elif index == PAGE_STATUS:
            load_icons(icon_view, icons.STATUS_ICONS)

        PAGES_LOADED.append(current_index)


    def slotPreparePage(self, widget):
        index = self.kjanus.activePageIndex()
        if index in PAGES_LOADED:
            print("[DEBUG] Already loaded page index {}".format(index))
            return

        current_page = self.kjanus.pageWidget(index)
        icon_view = current_page.child(b"icon_view")
        if icon_view is None:
            return

        if index == PAGE_ACTIONS:
            load_icons(icon_view, icons.ACTION_ICONS)
        elif index == PAGE_APPLICATIONS:
            load_icons(icon_view, icons.APPLICATION_ICONS)
        elif index == PAGE_CATEGORIES:
            load_icons(icon_view, icons.CATEGORY_ICONS)
        elif index == PAGE_DEVICES:
            load_icons(icon_view, icons.DEVICE_ICONS)
        elif index == PAGE_EMBLEMS:
            load_icons(icon_view, icons.EMBLEM_ICONS)
        elif index == PAGE_MEDIA_TYPES:
            load_icons(icon_view, icons.MEDIA_TYPE_ICONS)
        elif index == PAGE_PLACES:
            load_icons(icon_view, icons.PLACE_ICONS)
        elif index == PAGE_STATUS:
            load_icons(icon_view, icons.STATUS_ICONS)
        else:
            print("Unknown Page: {}".format(index))
            return

        PAGES_LOADED.append(index)

if __name__ == '__main__':
    appName = b"Icon Explorer"
    programName = b"Icon Explorer"
    version = b"0.1"
    description = b"An icon explorer for TQt/TDE."
    license = TDEAboutData.License_GPL_V3
    copyright = b"(c) 2024, 2025 mio"
    text = b"""Icon Explorer allows to you browse common system icons, organised by
category, and displays a short snippet of how to use the icon in your program."""
    homePage = b"https://codeberg.org/supercell/icon_explorer"
    bugEmail = b"stigma@disroot.org"

    aboutData = TDEAboutData(appName, programName, version, description,
                             license, copyright, text, homePage, bugEmail)

    TDECmdLineArgs.init(sys.argv, aboutData)
    app = TDEApplication ()
    mainWindow = MainWindow()
    mainWindow.show()
    sys.exit(app.exec_loop())
